package com.bjsxt.userscenter.users.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class copy
{
	public static void main(String[] args)
	{
		copyDirectory("D:/tmp","C:/Users/Administrator/Desktop");
	}

	//复制单个文件
	private static void copyFile(File sourceFile,File targetFile) throws IOException
	{
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff =null;
		
		//FileInputStream file = new FileInputStream(sourceFile);		
		//新建文件输入流
		try
		{
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
			//缓冲数组
			byte[] b = new byte[1024*5];
			int len;
			while((len = inBuff.read(b)) != -1)
			{
				outBuff.write(b, 0, len);
				outBuff.flush();
			}
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally
		{
			if(inBuff != null)
			{
				inBuff.close();
			}
			if (outBuff != null)
                outBuff.close();
		}
	}
	
	//复制目录
	private static void copyDirectory(String sourceDir, String targetDir)
	{
		//检查源目录
		File fSourceDir = new File(sourceDir);
		if(!fSourceDir.exists() || !fSourceDir.isDirectory())
		{
			return;
		}
		//是否存在目录
    	File fTargetDir = new File(targetDir);
    	if(!fTargetDir.exists())
    	{
    		fTargetDir.mkdirs();	
    	}
		//遍历文件夹
    	File[] file = fSourceDir.listFiles();
    	for (int i = 0; i < file.length; i++)
		{
			File sourceFile = file[i];
			//目标文件
			File targetFile = new File(fTargetDir, file[i].getName());
			try
			{
				copyFile(sourceFile, targetFile);
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//递归赋值子目录
			if(file[i].isDirectory())
			{
				// 准备复制的源文件夹
                String subSourceDir = sourceDir + File.separator + file[i].getName();
                // 准备复制的目标文件夹
                String subTargetDir = targetDir + File.separator + file[i].getName();
                // 复制子目录
                copyDirectory(subSourceDir, subTargetDir);
			}
		}
    	
	}
	
	
}